package chen.web;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;


public class SystemProperties {

	private static final String SQL_1 = "select p_value from web_properties where p_name = ?";
	private static final String SQL_2 = "update web_properties set p_value = ? where p_name = ?";
	private static final String SQL_3 = "insert into web_properties values(?, ?) ";
	private static final String SQL_4 = "select count(*) from web_properties where p_name = ?";
	
	private static SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(DataSourceProvider.getDataSource());;
	
	public static String getProperty(String name){
		String value = null;
		try{
		value = simpleJdbcTemplate.queryForObject(SQL_1, new RowMapper<String>(){
			@Override
			public String mapRow(ResultSet rs, int arg1) throws SQLException {
				// TODO Auto-generated method stub
				return rs.getString(1);
			}}, name);
		}catch(EmptyResultDataAccessException ex){
			
		}
		return value;
	}
	
	public static boolean exist(String name){
		int count = simpleJdbcTemplate.queryForInt(SQL_4, name);
		return count != 0;
	}
	
	public static void setProperty(String name, String value){
		if(exist(name)){
			simpleJdbcTemplate.update(SQL_2, value, name);
		} else {
			simpleJdbcTemplate.update(SQL_3, name, value);
		}
	}
}
